//
//  Created by Anna Sannikova on 7/6/11.
//  Copyright 2011. All rights reserved.
//

#import "ExecutorThread.h"

@implementation ExecutorThread

#pragma mark -

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
	[super dealloc];
}

#pragma mark -

- (void)main
{
 	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	NSTask *task;
	
	@try {
		task = [NSTask new];
		task.launchPath = [[NSBundle mainBundle] pathForResource:@"mystem" ofType:@""];
        NSLog(@"path to mystem: %s", [[NSBundle mainBundle] pathForResource:@"mystem" ofType:@""]);
		task.arguments = [NSArray arrayWithObjects:@"-c", @"-l", @"-e", @"utf-8", nil];
        
		m_inputPipe = [NSPipe new];
		m_outputPipe = [NSPipe new];
		task.standardInput = m_inputPipe;
		task.standardOutput = m_outputPipe;
		task.standardError = m_outputPipe;
		
		[task launch];
	}
	
	@catch (NSException *e)
	{
		if (e.description)
		{
            NSRunAlertPanel(@"Error!", @"Mystem execution failed: %@", @"OK", @"", @"",	e.description);
		}
        
		[task release];
        [m_inputPipe release];
		[m_outputPipe release];
		[pool release];
		return;
	}
	
	[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(taskDidTerminate:)
                                                 name:NSTaskDidTerminateNotification
                                               object:task];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(taskDataAvailable:)
                                                 name:NSFileHandleReadCompletionNotification
                                               object:nil];
    
	NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
	
	m_stopRunLoop = NO;
	while (m_stopRunLoop == NO
		   && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]);
	
	[task release];
	[m_outputPipe release];
	
	[pool release];
}


- (void)taskDidTerminate:(NSNotification *)notification
{
    NSLog(@"terminate");
	NSTask *task = (NSTask *)notification.object;
	
	NSFileHandle *handle = [m_outputPipe fileHandleForReading];
	NSData *data = [handle availableData];
	NSString *string = @"";
	
	if (data != nil && data.bytes != nil)
	{
		string = [[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding] autorelease];
	}
    
	m_stopRunLoop = YES;
	
	if (task.terminationStatus != 0)
	{
		NSRunAlertPanel(@"Error!", @"Mystem execution failed", @"OK", @"", @"");
	}	
}


- (void)taskDataAvailable:(NSNotification *)notification
{
    NSData *data = [[notification userInfo] objectForKey:@"NSFileHandleNotificationDataItem"];
    NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"%@", string);
}


- (void)sendString:(NSString *)string
{
    NSLog(@"write %@", string);
    [[m_inputPipe fileHandleForWriting] writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSData *data = [[m_outputPipe fileHandleForReading] availableData];
    NSString *string1 = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"%@", string1);
}    

@end
